﻿Imports System.IO

Public Class WorkerCard

  Public IDW As String = ""
  Public flSave As Boolean

  'флаги сохранений
  Private doSavePhoto As Boolean
  Private doSaveDetails As Boolean
  Private doSavePhones As Boolean

  'массив табов
  Private myTabPage As TabPage() = Nothing


  Private Sub WorkerCard_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'запоминаем табы
    myTabPage = New TabPage(tabC.TabPages.Count - 1) {}
    For i As Integer = 0 To tabC.TabPages.Count - 1
      myTabPage(i) = tabC.TabPages(i)
    Next


    If IDW <> "" Then 'редактирование карточки

      'основные сведения
      LoadMainData()

      If UserInfo.RightUser.ToUpper() = "ADMINKADR" Then

        'удаляем вкладки
        tabC.TabPages.Remove(tabPage2)
        tabC.TabPages.Remove(tabPage3)

      Else

        'телефоны
        'LoadPhones()

      End If

      ViewPhoto()

      doSaveDetails = False
      doSavePhoto = False
      doSavePhones = False

    Else
      ' новый сотрудник
      ID_WorkerLabel.Visible = False
      ID_Worker.Visible = False
      Foto.Visible = False
      btnFotoAdd.Visible = False
      tabC.TabPages.Remove(tabPage2)
      tabC.TabPages.Remove(tabPage3)
    End If

  End Sub


  ''' <summary>
  ''' Загрузка основных сведений сотрудника
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub LoadMainData()

    Dim sql As String
    sql = "SELECT Workers.F_Worker, Workers.N_Worker, Workers.P_Worker, Workers.I_Worker, Workers.Fl_Rel, Workers.Login, "
    sql += " Workers.ID_Post, Workers.ID_Otdel, Workers.PersonIndexDP, Posts.N_Post, Otdels.Name_Otdel "
    sql += " From Workers INNER JOIN "
    sql += " Posts ON Posts.ID_Post = Workers.ID_Post INNER JOIN "
    sql += " Otdels ON Otdels.ID_Otdel = Workers.ID_Otdel "
    sql += String.Format(" Where Workers.ID_Worker = {0}", IDW)

    Dim DRC As DataRowCollection = DB.GetFields(sql)

    If DRC.Count = 0 Then Exit Sub

    Dim dr As DataRow = DRC(0)

    FWorker.Text = dr("F_Worker").ToString()
    NWorker.Text = dr("N_Worker").ToString()
    PWorker.Text = dr("P_Worker").ToString()
    IWorker.Text = dr("I_Worker").ToString()

    Otdel.Text = dr("Name_Otdel").ToString()
    Otdel.Tag = dr("ID_Otdel").ToString()

    Post.Text = dr("N_Post").ToString()
    Post.Tag = dr("ID_Post").ToString()

    'код сотрудника
    ID_Worker.Text = IDW

    'персональный индекс делопроизводства
    IndexDP.Text = dr("PersonIndexDP").ToString()

    'логин
    Login.Text = dr("Login").ToString()

    initStatus(Val(dr("Fl_Rel")))

    ViewPhoto()

  End Sub

  ''' <summary>
  ''' Сохранение данных сотрудника
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub SaveCard()

    If CheckFields() = False Then Exit Sub

    Dim DataSet As New Dictionary(Of String, String)

    'основные данные:
    If doSaveDetails Then

      DataSet.Add("F_Worker", FWorker.Text)
      DataSet.Add("N_Worker", NWorker.Text)
      DataSet.Add("P_Worker", PWorker.Text)
      DataSet.Add("I_Worker", IWorker.Text)
      DataSet.Add("ID_Post", Post.Tag.ToString())
      DataSet.Add("ID_Otdel", Otdel.Tag.ToString())
      DataSet.Add("Fl_Rel", Status.SelectedIndex.ToString())
      DataSet.Add("PersonIndexDP", IndexDP.Text)
      DataSet.Add("Login", Login.Text)   'сетевые настройки:

      If IDW <> "" Then
        'обновляем основные данные
        DB.SetFields(DataSet, "Workers", "ID_Worker = " + IDW)
      Else

        'новый сотрудник
        Dim rs = DB.GetFields("SELECT ISNULL(MAX(ID_Worker), 0) + 1 AS NewID From Workers")
        IDW = (Convert.ToInt32(rs(0)("NewID")) + 1).ToString()
        DataSet.Add("ID_Worker", IDW)
        DB.InsertRow(DataSet, "Workers")
        If Params.UserInfo.RightUser.ToUpper() <> "ADMINKADR" Then
          tabC.TabPages.Clear()
          tabC.TabPages.AddRange(myTabPage)
        End If
        Foto.Visible = True
        btnFotoAdd.Visible = True
        ID_Worker.Text = IDW
        ID_Worker.Visible = True
        ID_WorkerLabel.Visible = True
        doSaveDetails = False
        Return

      End If

      doSaveDetails = False

    End If


    'фотография
    If doSavePhoto = True Then
      If Foto.Image Is Foto.ErrorImage Then
        DB.DeleteRow("WorkersPhoto", "ID_Worker = " + IDW)
      Else
        Dim imageArray As Byte()
        Using ms As New MemoryStream()
          'сохраняем изображение в массив байтов
          Foto.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
          imageArray = ms.ToArray()
        End Using

        Dim rs = DB.GetFields("SELECT ID_Worker, Photo_Worker From WorkersPhoto Where ID_Worker = " + IDW)

        If rs.Count > 0 Then
          DB.DeleteRow("WorkersPhoto", "ID_Worker = " + IDW)
        End If
        rs = Nothing

        'создание
        Dim DS = New Dictionary(Of String, Object)()
        DS.Add("ID_Worker", IDW)
        DS.Add("Photo_Worker", imageArray)
        DB.InsertByteRow(DS, "WorkersPhoto")

      End If
      doSavePhoto = False
    End If

    flSave = True

    Me.Close()

  End Sub


  ''' <summary>
  ''' Выбор новой фотографии сотрудника
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub AddPhoto()

    Dim OFD As New OpenFileDialog()

    OFD.Title = "Файл с фотографией сотрудника"
    OFD.Filter = "Изображение JPG (размер 175х130)|*.jpg;*.jpeg"

    If OFD.ShowDialog() = DialogResult.OK Then

      'превью:
      'Dim img As Image = Image.FromFile(OFD.FileName)
      Dim img As New Bitmap(OFD.FileName)
      Dim thumb As Image = img.GetThumbnailImage(260, 350, Function() False, IntPtr.Zero)

      thumb.Save(Path.ChangeExtension(OFD.FileName, "thumb"))
      Foto.Image = thumb
      btnFotoAdd.Text = "изменить фотографию"
      btnFotoDelete.Visible = True
      doSavePhoto = True

    End If

  End Sub

  ''' <summary>
  ''' Загрузка фотографии в память и отображение на форме
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub ViewPhoto()

    btnFotoDelete.Visible = False
    Dim DRC As DataRowCollection = DB.GetFields("SELECT ID_Worker, Photo_Worker From WorkersPhoto Where ID_Worker = " + IDW)

    If DRC.Count = 0 Then Exit Sub

    Dim dr As DataRow = DRC(0)
    Dim arrByte As Object = DirectCast(dr("Photo_Worker"), Byte())

    Using ms As New MemoryStream(arrByte, 0, arrByte.Length)
      ms.Write(arrByte, 0, arrByte.Length)
      Foto.Image = Image.FromStream(ms, True)
      btnFotoAdd.Text = "изменить фотографию"
      btnFotoDelete.Visible = True
    End Using


  End Sub


  ''' <summary>
  ''' Добавление статусов в компонент и выбор текущего статуса
  ''' </summary>
  ''' <param name="FlRel">ID выбранного статуса</param>
  ''' <remarks></remarks>
  Private Sub initStatus(ByVal FlRel As Integer)

    Status.Items.Clear()
    Status.Items.Add("Работает")
    Status.Items.Add("Уволен")
    Status.Items.Add("Командировка")
    Status.Items.Add("Отпуск")
    Status.Items.Add("Больничный")
    Status.Items.Add("Декрет")
    Status.Items.Add("Прочее")

    Status.SelectedIndex = FlRel

  End Sub


  ''' <summary>
  ''' Проверка заполнения обязательных полей
  ''' </summary>
  ''' <returns>True - все ок, False - есть ошибки</returns>
  ''' <remarks></remarks>
  Private Function CheckFields() As Boolean

    If FWorker.Text.Length = 0 Then
      SSPD.MsgErr("Не указана фамилия сотрудника")
      tabC.SelectedTab = tabPage1
      FWorker.Focus()
      Return False
    ElseIf NWorker.Text.Length = 0 Then
      SSPD.MsgErr("Не указано имя сотрудника")
      tabC.SelectedTab = tabPage1
      NWorker.Focus()
      Return False
    ElseIf IWorker.Text.Length = 0 Then
      SSPD.MsgErr("Не указаны инициалы сотрудника")
      tabC.SelectedTab = tabPage1
      IWorker.Focus()
      Return False
    ElseIf Otdel.Text = "" Then
      SSPD.MsgErr("Не выбран отдел")
      tabC.SelectedTab = tabPage1
      btnSelOtdel.Focus()
      Return False
    ElseIf Post.Text = "" Then
      SSPD.MsgErr("Не выбрана должность сотрудника")
      tabC.SelectedTab = tabPage1
      btnSelPost.Focus()
      Return False
    End If

    Return True

  End Function


  ''' <summary>
  ''' Выбор отдела
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub selOtdel()

    Dim sql As String
    sql = "SELECT ID_Otdel, Name_Otdel FROM Otdels"
    Dim sp As New SelectPar
    sp.SqlStr = sql
    sp.ColName = "Наименование отдела"
    sp.Text = "Выбор отдела"
    If Otdel.Tag.ToString() <> "" Then sp.SelID = Otdel.Tag.ToString()
    sp.ShowDialog()

    If sp.flSel Then

      Otdel.Text = sp.SelName
      Otdel.Tag = sp.SelValue

    End If

    sp.Dispose()

  End Sub


  ''' <summary>
  ''' Выбор отдела
  ''' </summary>
  ''' <remarks></remarks>
  Private Sub selPost()

    Dim sql As String
    sql = "SELECT ID_Post, N_Post FROM Posts"
    Dim sp As New SelectPar
    sp.SqlStr = sql
    sp.ColName = "Должность"
    sp.Text = "Выбор должности"
    If Post.Tag.ToString() <> "" Then sp.SelID = Post.Tag.ToString()
    sp.ShowDialog()

    If sp.flSel Then

      Post.Text = sp.SelName
      Post.Tag = sp.SelValue

    End If

    sp.Dispose()

  End Sub

  ''СОБЫТИЯ:

  Private Sub WorkerCard_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

    If e.KeyCode = Keys.Escape Then Me.Close()

    If e.KeyCode = Keys.F2 Then SaveCard()

  End Sub

  Private Sub WorkerCard_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing

    If doSaveDetails = True OrElse doSavePhoto = True OrElse doSavePhones = True Then
      If MessageBox.Show("Сохранить изменения?", "Карточка работника", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
        SaveCard()
        Me.Close()
      End If
    End If

  End Sub

  Private Sub btnFotoAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFotoAdd.Click

    AddPhoto()

  End Sub

  Private Sub btnFotoDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFotoDelete.Click

    If MessageBox.Show("Удалить фотографию сотрудника?", "Удаление фотографии", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = DialogResult.No Then
      Return
    End If
    Foto.Image = Foto.ErrorImage
    Foto.ImageLocation = Nothing
    btnFotoAdd.Text = "добавить фотографию"
    btnFotoDelete.Visible = False
    doSavePhoto = True

  End Sub

  Private Sub FWorker_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FWorker.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub NWorker_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NWorker.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub PWorker_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PWorker.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub IWorker_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IWorker.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub IndexDP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IndexDP.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub Status_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Status.SelectedIndexChanged
    doSaveDetails = True
  End Sub

  Private Sub Login_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Login.TextChanged
    doSaveDetails = True
  End Sub

  Private Sub МенюЗакрыть_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles МенюЗакрыть.Click

    Me.Close()

  End Sub

  Private Sub МенюСохранить_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles МенюСохранить.Click

    SaveCard()

  End Sub

  Private Sub tbtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbtnClose.Click

    Me.Close()

  End Sub

  Private Sub tbtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbtnSave.Click

    SaveCard()

  End Sub

  Private Sub btnSelOtdel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelOtdel.Click

    selOtdel()

  End Sub

  Private Sub Otdel_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Otdel.TextChanged

    doSaveDetails = True

  End Sub

  Private Sub Post_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Post.TextChanged

    doSaveDetails = True

  End Sub

  Private Sub btnSelPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelPost.Click

    selPost()

  End Sub

End Class